import {
  getIntegralGoods,
  signSetDay,
  userSignMsg,
  todaySign,
  userWalk,
  getUserIntegral,
  integralShopType,
  getIntegralCoupon,
  changeIntegralCoupon,
} from "@/api/modules/integral";

import {
  Component,
  Vue
} from "vue-property-decorator";
@Component({})
export default class IntegealMix extends Vue {

  /** 优惠券列表 */
  couponList: Array<any> = []
  /** 用户步数 */
  todayStep: number = 0
  /** 用户步数授权 */
  walkAuth: boolean = true
  /** 积分商品列表 */
  goodsList: Array<any> = []
  /** 是否有分页 */
  hasMore: boolean = false
  /** 签到天数 */
  signNeedDay: number = 0
  /** 商品列表查询条件 */
  query:any = {
    current: 1,
    size: 10,
    launchArea: "",
  }
  /** 连续签到天数(包含当天，当天未签到) */
  runningDays: string = ""
  /** 当前签到状态 */
  signInState: boolean = false
  /** 签到数组 */
  signArr: Array<any> = []
  /** 用户相关信息 */
  integral: number = 0
  avatarUrl: string = ""
  nickName: string = ""

  shop: any = {}
  singIn: any = {}
  stepNumber: number = 0

  getShopType() {
    integralShopType({}).then(res => {
      this.shop = res.shop
      this.singIn = res.singIn
      this.stepNumber = res.stepNumber
      if (res.shop) {
        if (res.singIn) {
          this.getDays();
        }
        if (res.stepNumber) {
          this.walkType();
        }
        this.getGoods();
      }
    });
  }

  /**
   * 获取商家设置签到天数
   */
  async getDays() {
    const res = await signSetDay({});
    this.signNeedDay = res;
    this.getUserSign();
  }

  /**
   * 获取用户签到信息
   */
  async getUserSign() {
    const signNeedDay = this.signNeedDay as any;
    const signNeedDayList = [] as any;
    for (const key in signNeedDay) {
      if (key) {
        signNeedDayList.push(key);
      }
    }
    const res = await userSignMsg({});
    const signArr = this.dealSignArr(res, signNeedDay, signNeedDayList);
    const numList = [] as any;
    signArr.forEach(item => {
      numList.push(item.value);
    });
    const maxName = this.findMost(numList);
    signArr.forEach(item => {
      if (item.value > maxName) {
        item.isAdd = true;
        item.addCode = item.value - maxName;
      }
    });
    this.runningDays = res.runningDays
    this.signArr = signArr
    this.signInState = res.signInState
  }

  /**
   * 获取签到最大值
   */
  findMost(arr) {
    const res = {};
    let maxName,
      maxNum = 0;
    arr.forEach(item => {
      res[item] ? (res[item] += 1) : (res[item] = 1);
    });
    for (const r in res) {
      if (res[r] > maxNum) {
        maxNum = res[r];
        maxName = r;
      }
    }
    return maxName;
  }

  /**
   * 处理签到信息
   */

  dealSignArr(res, signNeedDay, signNeedDayList) {
    const signArr = [] as any;
    const runningDays = Number(res.runningDays);
    for (let i = 0; i < signNeedDayList.length; i++) {
      signArr.push({
        type: runningDays - 1 >= i + 1 ? true : false,
        signInState: runningDays === i + 1 && !res.signInState ? true : false,
        value: Number(signNeedDay[i + 1].split(".")[0]),
        isAdd: false,
        addCode: 0,
      });
    }
    return signArr;
  }

  /**
   * 是否开启步数兑换
   */
  walkType() {
    if (!this.walkAuth) {
      return;
    }
    uni.authorize({
      scope: 'scope.werun',
      success: () => {
        uni.getWeRunData({
          success:res=>{
            this.getUserWalk(res);
            this.walkAuth = true
          },
          fail: () => {
            uni.showToast({
              title: '未授权获取步数',
              icon: 'none',
              mask: true
            })
            this.walkAuth = false;
          }
        });
      },
      fail: () => {
        uni.showToast({
          title: '未授权获取步数',
          icon: 'none',
          mask: true
        })
        this.walkAuth = false;
      }
    })
  }

  /**
   * 获取用户步数
   */
  getUserWalk(options) {
    const userInfo = this.$store.state.userStore.userInfo;
    const decryptRunData = {
      encryptedData: options.encryptedData,
      ivStr: options.iv,
      sessionKey: userInfo.sessionKey,
    };
    userWalk(decryptRunData).then(res => {
      this.todayStep = res
    });
  }

  /**
   * 获取积分商品
   */
  async getGoods(query = {}) {
    this.query = {
      ...this.query,
    }
    // this.query.launchArea = (infoExtends && infoExtends.prohibitStatus === "0") ? infoExtends.pointId : -1;
    if (this.hasMore) {
      return;
    }
    // Toast.loading({ duration: 10000 });
    const res = await getIntegralGoods(
      Object.assign({}, this.query, query),
    );
    res.list.forEach(item => {
      item.guidePrice =
        item.guidePrice && item.guidePrice > 0 ? item.guidePrice.toFixed(2) : 0;
    });

    const { current, pages, list } = res;
    this.goodsList = current > 1 ? [...this.goodsList, ...list] : list
    /** 如果为最后一页设置到底状态 */
    if (current === pages) {
      this.hasMore = true;
    }
  }

  /**
   * 用户签到操作
   */
  todaySignOpt() {
    todaySign({})
      .then(res => {
        this.$Popup.toast(`签到成功,获得${res}积分`);
      })
      .then(() => {
        this.getUserSign();
        this.getUser();
      });
  }

  /**
   * 获取用户积分信息
   */
  getUser() {
    getUserIntegral({}).then(res => {
      this.integral = res.integral
      this.avatarUrl = res.avatarUrl
      this.nickName = res.nickName
    });
  }

  /**
   * 获取积分优惠券
   */
  async getCoupon() {
    const list = [] as any;
    const res = await getIntegralCoupon({});
    res.forEach((item, index) => {
      item.hasUse = false;
      item.index = index;
      item.checkType = true;
      if (item.status === 1) {
        list.push(item);
      }
    });
    this.couponList = list
  }

  /**
   * 兑换积分优惠券
   */
  changeCoupon(e) {
    const id = e.currentTarget.dataset.coupon.id;
    const avaliable = e.currentTarget.dataset.coupon.totalAvailable;
    if (avaliable === 0) {
      return;
    }
    uni.showLoading({
      mask: true
    })
    changeIntegralCoupon(id, {})
      .then(() => {
        uni.showToast({ title: "兑换成功", icon: "none" });
        this.getUser();
        this.getCoupon();
        uni.hideLoading()
      })
      .catch(err => {
        uni.hideLoading()
        uni.showToast({ title: err, icon: "none" });
      });
  }

  /**
   * 查看积分商品详情
   */
  gotoDetail(e) {
    const id = e.currentTarget.dataset.good.id;
    uni.navigateTo({
      url: "/subcontract/pages/detail/integralGoods?id=" + id,
    });
  }

  /**
   * 步数兑换
   */
  gotoChange() {
    if (!this.walkAuth) {
      uni.openSetting({});
      this.walkType();
    } else {
      uni.navigateTo({
        url:
          "/subcontract/pages/integralShop/integralChange/integralChange?todayStep=" +
          this.todayStep,
      });
    }
  }

  /**
   * 商品详情
   */
  gotoBalance() {
    uni.navigateTo({
      url: "/subcontract/pages/balanceDetail/integralDetail",
    });
  }

  /**
   * 商品规则
   */
  gotoRule() {
    uni.navigateTo({
      url: "/subcontract/pages/integralShop/integralRule/integralRule",
    });
  }
}
